package com.bytedance.frameworks.baselib.network.http.cronet.a;

import android.content.Context;
import android.text.TextUtils;

import com.bytedance.common.utility.Logger;
import com.bytedance.frameworks.baselib.network.connectionclass.ConnectionSamplingClient;
import com.bytedance.frameworks.baselib.network.http.AppConfig;
import com.bytedance.frameworks.baselib.network.http.BaseRequestContext;
import com.bytedance.frameworks.baselib.network.http.BaseRequestInfo;
import com.bytedance.frameworks.baselib.network.http.c.SsHttpExecutor;
import com.bytedance.frameworks.baselib.network.http.cronet.ICronetClient;
import com.bytedance.frameworks.baselib.network.http.exception.HttpResponseException;
import com.bytedance.retrofit2.client.Client;
import com.bytedance.retrofit2.client.ClientCall;
import com.bytedance.retrofit2.client.Header;
import com.bytedance.retrofit2.client.Request;
import com.bytedance.retrofit2.client.SsResponse;
import com.bytedance.retrofit2.mime.TypedInput;
import com.bytedance.retrofit2.mime.TypedOutput;
import com.bytedance.retrofit2.mime.TypedString;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SsCronetHttpClient implements Client {
    private static String CRONET_CLIENT_CLASS_NAME = "";
    private static Context sContext;
    private static ICronetClient mCronetClient;
    private static volatile SsCronetHttpClient sInstance = null;
    private static a$b e;

    private SsCronetHttpClient(Context context) {
        sContext = context.getApplicationContext();
    }

    static int a(Request request, HttpURLConnection conn) throws IOException {
        int v0_1;
        if (request == null || conn == null) {
            v0_1 = -1;
        } else {
            TypedOutput v0 = request.body;
            if (v0 != null) {
                v0.writeTo(conn.getOutputStream());
            }

            v0_1 = conn.getResponseCode();
        }

        return v0_1;
    }

    static Context a() {
        return sContext;
    }

    public static SsCronetHttpClient getInstance(Context context) {
        if (sInstance == null) {
            synchronized (SsCronetHttpClient.class) {
                if (sInstance == null) {
                    sInstance = new SsCronetHttpClient(context);
                    loadCronetClient();
                }
            }
        }
        return sInstance;
    }

    private static <T> T a(Object arg1, Class<T> arg2, T arg3) {
        if (arg1 == null || !arg1.getClass().equals(arg2)) {
            return arg3;
        }
        return (T) arg1;
    }

    private static String a(Exception arg4) {
        if (arg4 == null) {
            String v0 = "";
            return v0;
        }

        try {
            String[] v0_2 = arg4.getMessage().split("\\|");
            if (v0_2 == null) {
                return "";
            }

            if (v0_2.length < 2) {
                return "";
            }

            if (Logger.debug()) {
                Logger.d("SsCronetHttpClient", "getHostAddress remoteIp = " + v0_2[0]);
            }

            return v0_2[0];
        } catch (Throwable v0_1) {
            v0_1.printStackTrace();
        }

        return "";
    }

    protected static HttpURLConnection openConnection(String url) throws IOException {
        loadCronetClient();
        AppConfig.f();
        if (mCronetClient != null) {
            ICronetClient cronetClient = mCronetClient;
            Context context = sContext;
            boolean enableHttpDns = e != null && e.a();
            HttpURLConnection connection = cronetClient.openConnection(context, url, enableHttpDns, AppConfig.getUserAgent(), new SsHttpExecutor());
            connection.setConnectTimeout(AppConfig.getConnectTimeout());
            connection.setReadTimeout(AppConfig.getReadWriteTimeout());
            return connection;
        }

        throw new IllegalArgumentException("CronetClient is null");
    }

    public static void a(a$b arg0) {
        e = arg0;
    }

    static void a(String arg9, long arg10, BaseRequestInfo arg12, String arg13, Exception arg14, HttpURLConnection arg15) {
        if (arg9 != null) {
            if (arg12 != null && (android.support.design.a.isTextEmpty(arg12.timingRemoteIP))) {
                SsCronetHttpClient.setRemoteIp(SsCronetHttpClient.a(arg14), arg12);
            }

            long v0 = System.currentTimeMillis() - arg10;
            arg12.requestEnd = System.currentTimeMillis();
            SsCronetHttpClient.getRequestMetrics(arg15, arg12);
            AppConfig.a(arg9, arg14);
            AppConfig.a(v0, arg10, arg9, arg13, arg12, arg14);
            if (arg15 == null) {
                return;
            }

            arg15.disconnect();
        }
    }

    private static void setRemoteIp(String remoteIp, BaseRequestInfo requestInfo) {
        if (!android.support.design.a.isTextEmpty(remoteIp) && requestInfo != null) {
            try {
                if (Logger.debug()) {
                    Logger.d("SsCronetHttpClient", "getRequestInfo remoteIp = " + remoteIp);
                }

                requestInfo.timingRemoteIP = remoteIp;
                if (requestInfo.requestContext != null) {
                    requestInfo.requestContext.remoteIp = remoteIp;
                }
            } catch (Throwable throwable) {
            }
        }
    }

    static void disconnect(HttpURLConnection connect) {
        if (connect != null && connect != null) {
            connect.disconnect();
        }
    }

    static void a(HttpURLConnection httpURLConnection, Request request) throws IOException {
        httpURLConnection.setRequestMethod(request.method);
        httpURLConnection.setDoInput(true);
        httpURLConnection.addRequestProperty("Accept-Encoding", "gzip");
        String userAgent = AppConfig.getUserAgent();
        if (!android.support.design.a.isTextEmpty(userAgent)) {
            if (mCronetClient != null) {
                userAgent = userAgent + " cronet/" + mCronetClient.getCronetVersion();
            }
            httpURLConnection.addRequestProperty("User-Agent", userAgent);
        }

        Iterator<Header> iterator = request.headers.iterator();
        while (iterator.hasNext()) {
            Header header = iterator.next();
            httpURLConnection.addRequestProperty(header.name, header.value);
        }

        TypedOutput typedOutput = request.body;
        if (typedOutput != null) {
            httpURLConnection.setDoOutput(true);
            httpURLConnection.addRequestProperty("Content-Type", typedOutput.mimeType());
            long length = typedOutput.length();
            if (length != -1) {
                httpURLConnection.setFixedLengthStreamingMode(((int) length));
                httpURLConnection.addRequestProperty("Content-Length", String.valueOf(length));
            } else {
                httpURLConnection.setChunkedStreamingMode(4096);
            }
        }
    }

    static byte[] a(String arg1, int arg2, HttpURLConnection arg3, long arg4, BaseRequestInfo arg6, String arg7, int arg8) throws IOException {
        return b(arg1, arg2, arg3, arg4, arg6, arg7, arg8);
    }

    protected static String getHeaderField(HttpURLConnection connection, String name) {
        if (connection == null || (TextUtils.isEmpty(name))) {
            return null;
        } else {
            String header = connection.getHeaderField(name);
            if (TextUtils.isEmpty(header)) {
                header = connection.getHeaderField(name.toLowerCase());
            }
            return header;
        }
    }

    private static void getRequestMetrics(HttpURLConnection connection, BaseRequestInfo requestInfo) {
        if (connection != null && requestInfo != null) {
            try {
                if (mCronetClient == null) {
                    return;
                }

                LinkedHashMap requestMetrics = new LinkedHashMap();
                mCronetClient.getRequestMetrics(connection, requestMetrics);
                if (requestMetrics.isEmpty()) {
                    return;
                }
                requestInfo.timingRemoteIP = a(requestMetrics.get("remote_ip"), String.class, "");
                requestInfo.timingDns = a(requestMetrics.get("dns_time"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingConnect = a(requestMetrics.get("connect_time"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingSsl = a(requestMetrics.get("ssl_time"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingSend = a(requestMetrics.get("send_time"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.pushTime = a(requestMetrics.get("push_time"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingReceive = a(requestMetrics.get("receive_time"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingIsSocketReused = a(requestMetrics.get("socket_reused"), Boolean.class, Boolean.valueOf(false)).booleanValue();
                requestInfo.timingWaiting = a(requestMetrics.get("ttfb"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingTotal = a(requestMetrics.get("total_time"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingTotalSendBytes = a(requestMetrics.get("send_byte_count"), Long.class, Long.valueOf(0)).longValue();
                requestInfo.timingTotalReceivedBytes = a(requestMetrics.get("received_byte_count"), Long.class, Long.valueOf(0)).longValue();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

    private static byte[] b(String arg11, int arg12, HttpURLConnection connection, long arg14, BaseRequestInfo requestInfo, String arg17, int statusCode) throws IOException {
        long v2_3;
        byte[] v2;
        String v8 = null;
        if (connection == null) {
            v2 = new byte[0];
        } else if (statusCode == 200) {
            requestInfo.fetchResponseTs = System.currentTimeMillis();
            boolean gzip = "gzip".equals(getHeaderField(connection, "Content-Encoding"));
            if (mCronetClient != null && (mCronetClient.isCronetHttpURLConnection(connection))) {
                gzip = false;
            }

            InputStream inputStream = connection.getInputStream();
            int[] v5 = new int[1];
            try {
                v5[0] = 0;
                v2 = android.support.design.a.unzipStream(gzip, arg12, inputStream, v5);
            } catch (Throwable v2_2) {
                android.support.design.a.closeQuietly(inputStream, v8);
                throw v2_2;
            }

            android.support.design.a.closeQuietly(inputStream, v8);
            byte[] v9 = new byte[v5[0]];
            System.arraycopy(v2, 0, v9, 0, v5[0]);
            if (android.support.design.a.hasSSMix(getHeaderField(connection, "Content-Type"))) {
                android.support.design.a.decodeBytes(v9, v9.length);
            }

            v2_3 = System.currentTimeMillis() - arg14;
            requestInfo.requestEnd = System.currentTimeMillis();
            getRequestMetrics(connection, requestInfo);
            AppConfig.b(arg11);
            AppConfig.a(v2_3, arg14, arg11, arg17, requestInfo);
            v2 = v9;
        } else {
            if (statusCode == 304) {
                requestInfo.fetchResponseTs = System.currentTimeMillis();
                v2_3 = System.currentTimeMillis() - arg14;
                requestInfo.requestEnd = System.currentTimeMillis();
                getRequestMetrics(connection, requestInfo);
                AppConfig.b(arg11);
                AppConfig.a(v2_3, arg14, arg11, arg17, requestInfo);
            }

            String v2_4 = connection.getResponseMessage();
            if (connection != null) {
                connection.disconnect();
            }

            throw new HttpResponseException(statusCode, v2_4);
        }
        return v2;
    }

    private static void loadCronetClient() {
        if (SsCronetHttpClient.mCronetClient == null) {
            String className = "org.chromium.CronetClient";
            if (!android.support.design.a.isTextEmpty(SsCronetHttpClient.CRONET_CLIENT_CLASS_NAME)) {
                className = SsCronetHttpClient.CRONET_CLIENT_CLASS_NAME;
            }

            try {
                Object cronetClientInstance = Class.forName(className).newInstance();
                if (!(cronetClientInstance instanceof ICronetClient)) {
                    return;
                }
                SsCronetHttpClient.mCronetClient = (ICronetClient) cronetClientInstance;
            } catch (Throwable throwable) {
                Logger.w("SsCronetHttpClient", "load CronetClient exception: " + throwable);
            }
        }
    }

    private static String getTTLogId(HttpURLConnection connection, BaseRequestInfo requestInfo) {
        if (connection == null) {
            return null;
        } else {
            setRemoteIp(getHeaderField(connection, "x-snssdk.remoteaddr"), requestInfo);
            return getHeaderField(connection, "X-TT-LOGID");
        }
    }

    public final ClientCall execute(Request request) throws IOException {
        return new CronetClientCall(request);
    }

    public interface a$b {
        boolean a();
    }

    public static final class CronetClientCall implements ClientCall {
        private HttpURLConnection httpURLConnection;
        private BaseRequestInfo baseRequestInfo;
        private long requestStartTime;
        private String d;
        private Request request;
        private boolean f;

        public CronetClientCall(Request request) throws IOException {
            this.baseRequestInfo = BaseRequestInfo.createRequestInfo();
            this.requestStartTime = 0L;
            this.d = null;
            this.f = false;
            this.request = request;
            String url = this.request.url;
            this.requestStartTime = System.currentTimeMillis();
            this.baseRequestInfo.requestStartTs = this.requestStartTime;
            try {
                this.httpURLConnection = SsCronetHttpClient.openConnection(url);
                if ((request.g instanceof BaseRequestContext)) {
                    this.baseRequestInfo.requestContext = (BaseRequestContext) request.g;
                    BaseRequestContext requestContext = this.baseRequestInfo.requestContext;
                    if (requestContext.timeout_connect > 0L || requestContext.timeout_read > 0L || requestContext.timeout_write > 0L) {
                        if (requestContext.timeout_connect > 0L) {
                            this.httpURLConnection.setConnectTimeout(((int) requestContext.timeout_connect));
                        }

                        if (requestContext.timeout_read > 0L) {
                            this.httpURLConnection.setReadTimeout(((int) requestContext.timeout_write));
                        }
                    }
                }

                if (this.request.isStreaming || ("GET".equals(this.request.method.toUpperCase())) || !"POST".equals(this.request.method.toUpperCase())) {
                    this.httpURLConnection.setInstanceFollowRedirects(true);
                } else {
                    this.httpURLConnection.setInstanceFollowRedirects(false);
                }

                SsCronetHttpClient.a(this.httpURLConnection, request);
            } catch (Exception e) {
                SsCronetHttpClient.a(url, this.requestStartTime, this.baseRequestInfo, this.d, e, this.httpURLConnection);
                this.f = true;
                if ((e instanceof IOException)) {
                    throw e;
                }
                throw new IOException(e.getMessage());
            }
        }

        private static List a(HttpURLConnection arg6) {
            List v0;
            if (arg6 == null) {
                v0 = null;
            } else {
                ArrayList v2 = new ArrayList();
                Iterator v3 = arg6.getHeaderFields().entrySet().iterator();
                label_8:
                while (v3.hasNext()) {
                    Object v0_1 = v3.next();
                    String v1 = (String) ((Map.Entry) v0_1).getKey();
                    Iterator v4 = ((List<String>) ((Map.Entry) v0_1).getValue()).iterator();
                    while (true) {
                        if (!v4.hasNext()) {
                            break;
                        }
                        ((List) v2).add(new Header(v1, (String) v4.next()));
                    }
                }
                v0 = v2;
            }
            return v0;
        }

        public final SsResponse execute() throws IOException {
            SsResponse v2_5;
            boolean v4;
            boolean v2_3;
            String v2_2;
            int v10;
            int v13 = 0;
            SsResponse v11 = null;
            int v12 = 0;
            String v3 = this.request.url;
            try {
                if (this.f) {
                    if (this.request.isStreaming) {
                        return null;
                    } else {
                        SsCronetHttpClient.disconnect(this.httpURLConnection);
                        return null;
                    }
                }
                if (SsCronetHttpClient.sContext != null && !android.support.design.a.isNetworkAvailable(SsCronetHttpClient.sContext)) {
                    if (!this.request.isStreaming) {
                        SsCronetHttpClient.disconnect(this.httpURLConnection);
                    }
                    return null;
                }
                if (!this.request.isStreaming) {
                    AppConfig.RxBytesSampleController v2_1 = AppConfig.getRxBytesSampleController();
                    if (v2_1 == null) {
                        v13 = 0;
                    } else if (v2_1.shouldSampleNet(v3)) {
                        ConnectionSamplingClient.getInstance().startSampling();
                        v13 = 1;
                    } else {
                        v13 = 0;
                    }
                } else {
                    v13 = 0;
                }
                v10 = SsCronetHttpClient.a(this.request, this.httpURLConnection);
                this.baseRequestInfo.responseBack = System.currentTimeMillis();
                this.baseRequestInfo.recycleCount = -1;
                this.d = SsCronetHttpClient.getTTLogId(this.httpURLConnection, this.baseRequestInfo);
                v2_2 = SsCronetHttpClient.getHeaderField(this.httpURLConnection, "Content-Type");
                TypedInput v7 = null;
                if (this.request.isStreaming) {
                    v2_2 = SsCronetHttpClient.getHeaderField(this.httpURLConnection, "Content-Encoding");
                    if (v2_2 == null) {
                        v2_3 = false;
                    } else if ("gzip".equalsIgnoreCase(v2_2)) {
                        v2_3 = true;
                    } else {
                        v2_3 = false;
                    }

                    if (SsCronetHttpClient.mCronetClient == null) {
                        v4 = v2_3;
                    } else if (SsCronetHttpClient.mCronetClient.isCronetHttpURLConnection(this.httpURLConnection)) {
                        v4 = false;
                    } else {
                        v4 = v2_3;
                    }
                    HttpURLConnection v5 = this.httpURLConnection;
                    SsCronetHttpResponse v2_4 = v5 == null || v5.getContentLength() == 0 ? null : new SsCronetHttpResponse(v5, v4);
                    v7 = v2_4;
                } else {
                    v7 = new TypedString(android.support.design.a.a(SsCronetHttpClient.a(v3, this.request.f, this.httpURLConnection, this.requestStartTime, this.baseRequestInfo, this.d, v10), v2_2));
                }
                v2_5 = new SsResponse(v3, v10, this.httpURLConnection.getResponseMessage(), CronetClientCall.a(this.httpURLConnection), ((TypedInput) v7));
                v2_5.requestInfo = this.baseRequestInfo;
                if (!this.request.isStreaming) {
                    SsCronetHttpClient.disconnect(this.httpURLConnection);
                }
                if (!this.request.isStreaming && v13 != 0) {
                    ConnectionSamplingClient.getInstance().stopSampling();
                }
                return v2_5;
            } catch (Exception v8) {
                v10 = v13;
                try {
                    label_101:
                    if ((v8 instanceof NullPointerException)) {
                        if (!"Response info is null when there is no exception.".equals(v8.getMessage())) {

                        } else {
                            if (!this.request.isStreaming) {
                                SsCronetHttpClient.disconnect(this.httpURLConnection);
                            }

                            if (this.request.isStreaming) {
                                return v11;
                            }

                            if (v10 == 0) {
                                return v11;
                            }

                            ConnectionSamplingClient.getInstance().stopSampling();
                            return v11;
                        }
                    }

                    if ((v8 instanceof HttpResponseException)) {
                        Exception v2_6 = v8;
                        if (((HttpResponseException) v2_6).getStatusCode() == 304) {
                            throw v2_6;
                        }
                    }

                    SsCronetHttpClient.a(v3, this.requestStartTime, this.baseRequestInfo, this.d, v8, this.httpURLConnection);
                    if ((v8 instanceof IOException)) {
                        throw v8;
                    }

                    throw new IOException(v8.getMessage());
                } catch (Throwable v2) {
                    if (!this.request.isStreaming || v12 != 0) {
                        SsCronetHttpClient.disconnect(this.httpURLConnection);
                    }

                    if (!this.request.isStreaming && v13 != 0) {
                        ConnectionSamplingClient.getInstance().stopSampling();
                    }
                }
            }
            return null;
        }

        public final void cancel() {
            if (this.httpURLConnection != null) {
                this.httpURLConnection.disconnect();
                this.f = true;
            }
        }

        public final Request request() {
            return this.request;
        }
    }
}

